package com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.callback;

import android.content.Intent;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import androidx.annotation.RequiresApi;
import android.util.Log;


import com.cn.ZhiKeDianShang.base.GlobalApp;
import com.cn.ZhiKeDianShang.ui.activity.LoginActivity;
import com.cn.ZhiKeDianShang.util.LogUtil;
import com.cn.ZhiKeDianShang.util.ToastUtil;
import com.cn.ZhiKeDianShang.xuanhttplibrary.okhttp.HttpUtils;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;


/**
 * @author Administrator
 * @time 2017/3/30 0:45
 * @des ${TODO}
 */

public abstract class JsonCallback implements Callback {

    private Handler mDelivery;

    public JsonCallback() {
        mDelivery = new Handler(Looper.getMainLooper());
    }

    public abstract void onResponse(String result);

    public abstract void onError(Call call, Exception e);

    @Override
    public void onFailure(Call call, IOException e) {
        Log.i(HttpUtils.TAG, "服务器请求失败", e);
        errorData(call, e);
    }

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    public void onResponse(Call call, Response response) throws IOException {
        if (response.code() == 200) {
            try {
                String datainfo = response.body().string();
                LogUtil.i(HttpUtils.TAG, "没解密之前返回的数据：" + datainfo);
                successData(datainfo);
            } catch (Exception e) {
                LogUtil.i(HttpUtils.TAG, "数据解析异常:" + e.getMessage());
                errorData(call, new Exception("数据解析异常"));
            }
        }else if (response.code() == 401){
            Intent intent = new Intent(GlobalApp.getAppContext(), LoginActivity.class);
            // 清空activity栈，
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            GlobalApp.getAppContext().startActivity(intent);
            Looper.prepare();
            ToastUtil.showShort("登录过期，请重新登陆");
            Looper.loop();
        } else {
            LogUtil.i(HttpUtils.TAG, "服务器请求异常");
            errorData(call, new Exception("服务器请求异常"));
        }
    }

    protected void successData(final String data) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                onResponse(data);
            }
        });
    }

    protected void errorData(final Call call, final Exception e) {
        mDelivery.post(new Runnable() {
            @Override
            public void run() {
                onError(call, e);
            }
        });
    }
}
